package routers

import (
	"net/http"
	"strconv"

	"github.com/labstack/echo"
	"shqsoft.cn/pasnj/base"
)

//IndiAccoDiviCard 对公认定
type IndiAccoDiviCard struct {
	Bgqdivi []IndiAccoDivi `json:"Bgqdivi"`
	Bghdivi []IndiAccoDivi `json:"Bghdivi"`
}

//IndiAccoDivi 首页相应
type IndiAccoDivi struct {
	DPNM string   `json:"DPNM"`
	EMNM string   `json:"EMNM"`
	DSVL *float64 `json:"DSVL"`
}

// //获取对公认定原客户经理
func getIndiAccoBgqDivi(runid int) ([]IndiAccoDivi, error) {
	sqlStr := `select  c.DPNM DPNM,c.EMNM EMNM,a.BSVL*100 DSVL from 
	T_INDI_CLIE_YGFC a inner join T_INDI_CLIE_DIVI2 B ON A.CUID=B.CUID
	inner join DIM_USER c on a.EMID=c.EMID where  A.DTID=dbo.GetDateToInt(DATEADD(DD,-1,B.CREATETIME))  and  B.FRID=?`
	rows, err := base.DB.Raw(sqlStr, runid).Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	bgqdivi := make([]IndiAccoDivi, 0)
	for rows.Next() {
		var cad IndiAccoDivi
		rows.Scan(&cad.DPNM, &cad.EMNM, &cad.DSVL)
		bgqdivi = append(bgqdivi, cad)
	}
	return bgqdivi, nil
}

// 获取对公认定现客户经理
func getIndiAccoBghDivi(runid int) ([]IndiAccoDivi, error) {
	sqlStr := `select b.DPNM as DPNM,b.EMNM EMNM,a.DSVL1 DSVL from 
	(select EMID1,DSVL1 from T_INDI_CLIE_DIVI2  where frid=? and EMID1>0
	union all
	select EMID2,DSVL2 from T_INDI_CLIE_DIVI2  where frid=? and EMID2>0
	union all
	select EMID3,DSVL3 from T_INDI_CLIE_DIVI2  where frid=? and EMID3>0) a inner join DIM_USER b on a.EMID1=b.EMID `
	rows, err := base.DB.Raw(sqlStr, runid, runid, runid).Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	bghdivi := make([]IndiAccoDivi, 0)
	for rows.Next() {
		var cad IndiAccoDivi
		rows.Scan(&cad.DPNM, &cad.EMNM, &cad.DSVL)
		bghdivi = append(bghdivi, cad)
	}
	return bghdivi, nil
}

//获取对公认定的客户经理
func getIndiAccoDiviRouter(c echo.Context) error {
	runidStr := c.Param("runID")
	runID, err := strconv.Atoi(runidStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "runID不能为空，且必须为Int！")
	}
	accobgq, err := getIndiAccoBgqDivi(runID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	accobgh, err := getIndiAccoBghDivi(runID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	accodivi := IndiAccoDiviCard{
		Bgqdivi: accobgq,
		Bghdivi: accobgh,
	}
	return c.JSON(http.StatusOK, accodivi)
}
